<script setup>
import { ref, defineProps, defineEmits, onMounted, watch, onUnmounted } from "vue";
import JSEncrypt from "jsencrypt";
import { authLogin, authRegister, getAuthCaptcha, getPublicKey, getWechatAuthUrl, getWechatAuthLogin } from "@/api/auth";
import VerifyBox from '@/components/VerifyBox.vue'
import { useUserStore } from '~/stores/user'
import { useRouter } from 'vue-router'
import { Back } from '@element-plus/icons-vue'
import passwordValidator from '@/utils/passwordValidator'

const userStore = useUserStore()
const router = useRouter()

const props = defineProps({
  loginShow: {
    type: Boolean,
    default: false
  },
  isLogin: {
    type: Boolean,
    default: true
  },
});

const emits = defineEmits(["update:loginShow", "update:isLogin"]);

const verify = ref(null) // 验证码组件
const userName = ref('') // 用户名
const password = ref('') // 密码
const captchaVerification = ref(null) // 注册后token拼接验证码
const captcha = ref(null); // 验证码
const captchaKey = ref(null); // 验证码key
const captchaImg = ref(null); // 验证码图片

// 密码强度相关
const passwordStrength = ref(0)
const strengthLevel = ref({ level: '', className: '', color: '' })

const captchaType = ref('') // 验证码类型
const errorTips = ref('') // 错误提示
const formRef = ref(null) // 表单ref

// 密码验证函数
const validatePassword = (rule, value, callback) => {
  if (!value) {
    callback(new Error('请输入密码'))
    return
  }

  const result = passwordValidator.validate(value)
  if (!result.valid) {
    callback(new Error(result.message))
    return
  }

  callback()
}

// 表单校验规则
const rules = {
  userName: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: '@change' },
    {
      pattern: /^[a-zA-Z0-9_]+$/,
      message: '用户名只能包含英文和数字',
      trigger: 'blur'
    }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { validator: validatePassword, trigger: 'change' }
  ],
  captcha: [
    { required: true, message: '请输入验证码', trigger: 'blur' }
  ]
}

const onShow = (type) => {
  captchaType.value = type
  verify.value.show()
}

const reset = () => {
  userName.value = '';
  password.value = '';
  captcha.value = null;
  strengthLevel.value = { level: '', className: '', color: '' }
}

const changeIsLoginType = (type) => {
  reset();
  emits('update:isLogin', type);
  errorTips.value = '';
  if (type) {
    // 如果是登录,获取验证码
    getAuthCaptchaFun();
  } else {

  }
}

const showCaptchaBox = ref(false) // 是否展示滑块

// 显示滑块弹窗
const showCaptchaBoxFun = async () => {
  await formRef.value.validate()
  showCaptchaBox.value = true;
  setTimeout(() => {
    onShow('blockPuzzle')
  }, 100)
}

// 登录
const login = async () => {
  if (!formRef.value) return

  try {
    await formRef.value.validate()
    const publicKey = await getPublicKeyFun();
    console.log(publicKey)
    const encrypt = new JSEncrypt();
    encrypt.setPublicKey(publicKey);
    const encryptedPassword = encrypt.encrypt(password.value)
    const params = {
      userName: userName.value,
      password: encryptedPassword,
      captcha: captcha.value,
      captchaKey: captchaKey.value,
    }
    const res = await authLogin(params)
    console.log('login------------', res)
    if (res.suc) {
      setToken(res.data.t);

    } else {
      errorTips.value = res.msg;
      await getAuthCaptchaFun();
    }
  } catch (err) {
    return;
    if (err.message) {
      errorTips.value = err.message;
    } else {
      errorTips.value = err.msg;
    }
    await getAuthCaptchaFun();
  }
}


const setToken = (token) => {
  localStorage.setItem('token', token);
  userStore.updateUser({
    id: "",
    token: token
  })
  setTimeout(() => {
    closeDialog();
  }, 100)
}

// 注册
const authRegisterFun = async () => {
  if (!formRef.value) return

  try {
    await formRef.value.validate()
    const publicKey = await getPublicKeyFun();
    console.log(publicKey)
    const encrypt = new JSEncrypt();
    encrypt.setPublicKey(publicKey);
    const encryptedPassword = encrypt.encrypt(password.value)
    const registerForm = {
      userName: userName.value,
      password: encryptedPassword,
      captchaVerification: captchaVerification.value,
    }
    const res = await authRegister(registerForm)
    console.log(res)
    if (res.suc) {
      password.value = '';
      // changeIsLoginType(true);
      // showCaptchaBox.value = true;
      setToken(res.data.t);
    } else {
      errorTips.value = res.msg;
    }
  } catch (err) {
    if (err.message) {
      errorTips.value = err.message;
    } else {
      errorTips.value = err.msg;
    }
  }
}

// 登录时获取五位验证码
// eslint-disable-next-line
const getAuthCaptchaFun = async () => {
  captcha.value = null;
  const res = await getAuthCaptcha();
  console.log(res);
  captchaImg.value = res.data.image;
  captchaKey.value = res.data.key;
}

// 登录时获取公钥
// eslint-disable-next-line
const getPublicKeyFun = async () => {
  const res = await getPublicKey();
  console.log(res)
  return res.data
}

// 注册
const success = async (val) => {
  console.log('captchaVerification home', val)
  captchaVerification.value = val.captchaVerification;
  await authRegisterFun();
}

const validateUsername = (value) => {
  // 只允许英文、数字、下划线和@，且必须包含英文和数字
  const reg = /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z0-9_@]*$/;
  if (!reg.test(value)) {
    // 如果输入了不允许的字符，则移除这些字符
    userName.value = value.replace(/[^a-zA-Z0-9_@]/g, '');
  }
}

// 关闭弹窗
const closeDialog = () => {
  emits('update:loginShow', false);
  userStore.setShowLoginDialog(false);
}

const showVxContent = ref(false);

watch(
  () => userStore.showLoginDialog,
  (newVal) => {
    loginDialogShow.value = newVal
    // 当弹窗关闭时
    if (!newVal) {
      // 检查登录状态
      if (userStore.token) {
        // 登录成功，使用 router.replace 保持当前路由
        router.replace(router.currentRoute.value.fullPath)
      } else {
        // 未登录成功，只在个人中心页面时跳转到首页
        const currentPath = window.location.pathname
        if (currentPath.startsWith('/userPage')) {
          router.push('/')
        }
      }
    }
  }
)

const setSrc = ref('')

const showVxContentFun = async () => {
  showVxContent.value = true;
  const res = await getWechatAuthUrl();
  console.log(res)
  setSrc.value = res.data.authUrl
}


const vxCode = ref('')
const vxState = ref('')
const vxUrl = ref('')


const changeVxUrl = (val) => {
  // 将val中code 和state提取出来 
  const code = val.split('code=')[1].split('&')[0]
  const state = val.split('state=')[1].split('&')[0]
  vxCode.value = code
  vxState.value = state
}

const handleVxLogin = async () => {
  const res = await getWechatAuthLogin({
    code: vxCode.value,
    state: vxState.value
  });
  console.log(res)
  if (res.suc) {
    localStorage.setItem('token', res.data.t);
    userStore.updateUser({
      id: "",
      token: res.data.t
    })
    setTimeout(() => {
      closeDialog();
    }, 500)
  }
}




// 添加消息监听器
const handleMessage = (event) => {
  // 验证消息来源 - 支持子域名
  const currentOrigin = window.location.origin;
  const eventOrigin = event.origin;

  // 检查是否是相同的域名（包括子域名）
  if (!eventOrigin.endsWith('.gotosea123.com') && eventOrigin !== 'gotosea123.com') {
    return;
  }

  if (event.data && event.data.type === 'wechat_login') {
    const code = event.data.code;
    const state = event.data.state;
    console.log('收到微信授权码:', code);
    vxCode.value = code;
    vxState.value = state;
    handleVxLogin();
  }
}

onMounted(() => {
  console.log(props.loginShow)
  if (props.isLogin) {
    // 如果是登录,获取验证码
    getAuthCaptchaFun()
  } else {
    // 如果是注册,显示滑块
    // onShow('blockPuzzle')
  }
  // 添加消息监听
  window.addEventListener('message', handleMessage);
})


onUnmounted(() => {
  // 移除消息监听
  window.removeEventListener('message', handleMessage);
})

// 监听密码变化
watch(password, (newVal) => {
  if (!props.isLogin) { // 只在注册时计算密码强度
    passwordStrength.value = passwordValidator.getStrengthScore(newVal)
    strengthLevel.value = passwordValidator.getStrengthLevel(passwordStrength.value)
  }
})

</script>

<template>
  <div class="login-modal">
    <div class="login-container">
      <div class="login-header">
        <span class="close-btn" @click="closeDialog">
          <svg width="32" height="32" viewBox="0 0 32 32" fill="none" xmlns="http://www.w3.org/2000/svg">
            <path d="M9.3335 9.33333L22.6668 22.6667" stroke="currentColor" stroke-width="2" stroke-linecap="round"
              stroke-linejoin="round"></path>
            <path d="M9.3335 22.6667L22.6668 9.33333" stroke="currentColor" stroke-width="2" stroke-linecap="round"
              stroke-linejoin="round"></path>
          </svg>
        </span>
      </div>
      <div class="login-logo">
        <div class="logo-text"></div>
      </div>
      <div class="login-content" v-if="!showVxContent">
        <div class="login-tabs">
          <div class="tab-item" @click="changeIsLoginType(!isLogin)" :class="{ 'active': isLogin === true }">登录</div>
          <div class="tab-item" @click="changeIsLoginType(!isLogin)" :class="{ 'active': isLogin === false }">注册</div>
        </div>
        <el-form ref="formRef" @submit.prevent :model="{ userName, password, captcha }" :rules="rules"
          class="login-form">
          <span class="error-tips" v-if="errorTips">{{ errorTips }}</span>
          <template v-if="isLogin">
            <el-form-item>
              <el-input class="input-field" v-model="userName" size="small" :placeholder="'请输入登录名'" />
            </el-form-item>
            <el-form-item>
              <el-input size="small" v-model="password" show-password type="password" placeholder="请输入登录密码" />
            </el-form-item>
            <el-form-item prop="captcha">
              <div class="captcha-item">
                <el-input size="small" @keyup.enter="login()" class="captcha-input" v-model="captcha"
                  placeholder="请输入验证码" />
                <el-image :src="captchaImg" @click="getAuthCaptchaFun()" class="captcha-img" :fit="fit" />
              </div>
            </el-form-item>
            <div class="forgot-password" v-if="false">
              忘记登录密码?
            </div>
          </template>
          <template v-else>
            <el-form-item prop="userName">
              <el-input class="input-field" v-model="userName" size="small"
                :placeholder="'请输入用户登录名称(只允许英文、数字和下划线组合)'" />
            </el-form-item>
            <el-form-item prop="password">
              <el-input size="small" v-model="password" show-password type="password"
                :placeholder="'请设置8-20位密码，必须包含数字、小写字母、大写字母、特殊字符中的至少三种'" />
            </el-form-item>
            <div class="password-strength">
              <div class="strength-bar">
                <div class="strength-progress"
                  :style="{ width: passwordStrength + '%', backgroundColor: strengthLevel.color }"></div>
              </div>
              <span class="strength-text" :style="{ color: strengthLevel.color }">密码强度：{{ strengthLevel.level }}</span>
            </div>
          </template>

          <VerifyBox class="verify-box" v-if="!isLogin && showCaptchaBox" mode="pop" @success="success"
            :captchaType="captchaType" :imgSize="{ width: '100%', height: '200px' }" ref="verify"></VerifyBox>
          <div class="login-btn" v-if="isLogin">
            <el-button type="primary" @click="login()">登录</el-button>
          </div>
          <div class="login-btn" v-else>
            <el-button type="primary" @click="showCaptchaBoxFun()">注册</el-button>
          </div>
          <div class="login-tip">
            未注册过的手机号将自动创建账号，登录即表示阅读并同意<span class="privacy-link">《用户协议及隐私政策》</span>
          </div>

        </el-form>
      </div>
      <div v-else>
        <div v-if="else">
          {{ setSrc }}
          vxCode: {{ vxCode }}
          vxState: {{ vxState }}
          <el-input type="textarea" rows="3" @change="changeVxUrl" v-model="vxUrl" placeholder="请输入回调url"></el-input>
          <el-input v-model="vxCode" placeholder="请输入微信授权码"></el-input>
          <el-input v-model="vxState" placeholder="请输入微信授权状态"></el-input>
          <el-button @click="handleVxLogin">微信授权登录</el-button>
        </div>
        <iframe style="margin: 0 auto;" sandbox="allow-scripts allow-top-navigation allow-same-origin" scrolling="no"
          width="290" height="400" frameBorder="0" allowTransparency="true" :src="setSrc"></iframe>
      </div>
      <div class="social-login">
        <div class="divider">
          <i></i><span>更多登录方式</span><i></i>
        </div>
        <div class="social-icons" v-if="!showVxContent">
          <button class="wechat-btn" @click="showVxContentFun">
            <img src="~/assets/images/activity/share1.png" alt="咨询">
          </button>
        </div>
        <div class="social-icons" v-else>
          <button @click="showVxContent = false" style="display: flex;align-items: center;color: #666;">
            <el-icon>
              <Back />
            </el-icon>
            <span style="margin-left: 10px;">返回账号密码登录</span>
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
.login-modal {
  position: fixed;
  left: 0;
  top: 0;
  width: 100%;
  height: 100vh;
  overflow: hidden;
  z-index: 999;
  display: flex;
  justify-content: center;
  align-items: center;
  background: rgba(17, 24, 39, .3);
  -webkit-backdrop-filter: blur(14px);
  backdrop-filter: blur(14px);
  z-index: 9999;
}

.login-container {
  width: 520px;
  padding: 56px 42px 36px;
  position: relative;
  background: #fff;
  border-radius: 12px;
  animation: open .3s cubic-bezier(.175, .885, .32, 1.275);
}

.login-header {
  position: absolute;
  top: 24px;
  right: 20px;
}

.close-btn {
  cursor: pointer;
  color: #adb5bd;
}

.login-logo {
  display: flex;
  justify-content: center;
  margin-bottom: 24px;
}

.logo-text {
  background: url("@/assets/images/logo/login-title2.png");
  width: 272px;
  height: 82px;
  background-size: 100% 100%;
}

.login-content {
  >>>.el-form-item__content {
    margin-bottom: 10px;
    border-bottom: 1px solid #d1d5db !important;
  }

  >>>.el-input__wrapper {
    box-shadow: none !important;
    font-size: 16px;
    color: #333;
    padding-left: 0;
    padding-right: 0;
  }

  >>>.el-input__inner {
    font-size: 16px;
    color: #333;
  }
}

.login-tabs {
  display: flex;
  justify-content: center;
  background-color: #f9f9fc;
  border-radius: 30px;
  padding: 4px;
  margin-bottom: 24px;
}

.tab-item {
  padding: 7px 0;
  width: 108px;
  text-align: center;
  border-radius: 30px;
  color: #9c9ea3;
  cursor: pointer;
  font-size: 14px;
}

.tab-item.active {
  background-color: #fff;
  box-shadow: 0 0 4px rgba(0, 0, 0, 0.06);
  color: #111827;
}

.login-form {
  width: 100%;
}

.error-tips {
  color: #ff4d4f;
  font-size: 14px;
  margin-bottom: 16px;
  display: block;
}

.form-item {
  margin-bottom: 24px;
  border-bottom: 1px solid #d1d5db !important;
  padding-bottom: 10px;
}

:deep(.el-input__inner::placeholder) {
  font-size: 12px;
}

.form-item:focus-within {
  border-bottom-color: #111827;
}

.captcha-item {
  position: relative;
  display: flex;
  justify-content: space-between;
  width: 100%;
}

.captcha-img {
  position: absolute;
  right: 0;
  top: -21px;
  width: 100px;
  height: 44px;
  cursor: pointer;
}

.forgot-password {
  text-align: right;
  color: #666;
  cursor: pointer;
  margin-bottom: 24px;
}

.login-btn {
  margin-top: 10px;
}

.login-btn button {
  width: 100%;
  height: 48px;
  background: linear-gradient(263deg, #004FD9 0%, #33A0FF 96%);
  color: #fff;
  font-size: 16px;
  border-radius: 60px;
  cursor: pointer;
  border: none;
}

.login-tip {
  font-size: 12px;
  color: #5d6266;
  margin-top: 14px;
  text-align: center;
}

.privacy-link {
  color: #1B7AED;
  cursor: pointer;
}

.social-login {
  margin-top: 26px;
}

.divider {
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 12px;
}

.divider i {
  width: 46px;
  border-bottom: 1px solid #e5e7eb;
}

.divider span {
  color: #adb5bd;
  margin: 0 12px;
  font-size: 12px;
}

.social-icons {
  display: flex;
  justify-content: center;
}

.wechat-btn {
  width: 36px;
  height: 36px;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #f9f9fc;
  border-radius: 50%;
  color: #07c160;
  transition: all .3s;
  border: none;
  cursor: pointer;
}

.wechat-btn:hover {
  background-color: rgba(7, 193, 96, 0.1);
  color: #fff;
}

@keyframes open {
  0% {
    transform: scale(.8);
  }

  100% {
    transform: scale(1);
  }
}

@media only screen and (max-width: 767px) {
  .login-container {
    width: 335px;
    padding: 32px;
  }

  .logo-text {
    width: 182px;
    height: 54px;
  }

  .tab-item {
    width: 96px;
    padding: 5px 0;
    font-size: 13px;
  }

  .form-item {
    border: 1px solid #d1d5db;
    padding: 10px 16px;
    border-radius: 4px;
    margin-bottom: 20px;
  }

  .form-item:focus-within {
    border-color: #111827;
  }

  .login-btn button {
    height: 44px;
  }

  .social-login {
    /* display: none; */
  }
}

:deep(.el-form-item__error) {
  color: #ff4d4f;
  font-size: 12px;
  margin-top: 4px;
}

.password-strength {
  margin-top: 8px;
  width: 100%;
}

.strength-bar {
  height: 4px;
  background-color: #f0f0f0;
  border-radius: 2px;
  overflow: hidden;
}

.strength-progress {
  height: 100%;
  transition: all 0.3s ease;
}

.strength-text {
  font-size: 12px;
  margin-top: 4px;
  display: block;
  color: #666;
}
</style>